package com.ciwong.epaper.modules.me.ui;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.application.EpagerErrcode;
import com.ciwong.epaper.application.EpaperConstant;
import com.ciwong.epaper.bean.HideDownloadDialogBean;
import com.ciwong.epaper.event.EventBusFactory;
import com.ciwong.epaper.modules.epaper.bean.Answer;
import com.ciwong.epaper.modules.epaper.bean.BasePaging;
import com.ciwong.epaper.modules.me.adapter.HomeWorkAdapter;
import com.ciwong.epaper.modules.me.bean.Clazz;
import com.ciwong.epaper.modules.me.bean.MyWork;
import com.ciwong.epaper.modules.me.bean.WorkContents;
import com.ciwong.epaper.modules.me.dao.MeDao;
import com.ciwong.epaper.modules.me.presenter.HomeWorkPresenter;
import com.ciwong.epaper.modules.me.presenter.HomeWorkRelatPresenter;
import com.ciwong.epaper.modules.me.ui.interfaces.IHomeWorkFragment;
import com.ciwong.epaper.modules.me.util.MeJumpManager;
import com.ciwong.epaper.util.DialogUtil;
import com.ciwong.epaper.util.DoubleClickCheckUtils;
import com.ciwong.epaper.util.EJumpManager;
import com.ciwong.epaper.util.FeedbackUtil;
import com.ciwong.epaper.util.IntentValue;
import com.ciwong.epaper.util.RequestCode;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.epaper.util.download.DownLoadInfo;
import com.ciwong.epaper.widget.PullToRefreshView;
import com.ciwong.eventbus.EventBus;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.ciwong.mobilelib.utils.XXPermissionTool;
import com.ciwong.mobilelib.widget.CWDialog;
import com.ciwong.mobilelib.widget.DownloadProgressBar;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;

public class ErrorWorkActivity extends BaseActivity implements PullToRefreshView.OnHeaderRefreshListener, IHomeWorkFragment,
        PullToRefreshView.OnFooterRefreshListener, ExpandableListView.OnGroupClickListener, ExpandableListView.OnChildClickListener {

    private EApplication application;
    private static final String TAG = "ErrorWorkActivity";

    private final int NET_ERROR_TIP = 3;
    private final int DISMISS_NET_ERROR_TIP = 4;

    public boolean isTheLastPageShow = false;

    /**
     * 刷新ListView
     */
    private PullToRefreshView my_work_refresh_view;
    /**
     * 可扩展ListView
     */
    private ExpandableListView expandableListView;

    /**
     * 没有数据时显示的界面
     */

    private RelativeLayout ll_no_data;

    private TextView btn_join_class, mTvPlaceHold;


    private View handle_join_class, handle_go_to_bookdesk;

    private TextView tv_net_tips, mTvNoDataTips;

    /**
     * 数据集合
     */
    public List<MyWork> myWorks = new ArrayList<MyWork>();
    /**
     * 数据适配器
     */
    public HomeWorkAdapter mHomeWorkAdapter;
    /**
     * 默认从第一页开始加载
     */
    private final int defult_page = 1;

    /**
     * 当前页码
     */
    private int curPage = defult_page;

    /**
     * 默认加载数据大小
     */
    private static final int LOAD_PAGE_SIZE = 10;

    /**
     * 是否是刷新状态,true为刷新，false为加载更多
     */
    private boolean isRefresh = true;
    private int mPageCount = -1;

    private boolean isGetDataFromNet = false;
    private boolean isGetLocalSuccess = false;
    private LinearLayout mFootViewParent;
    private HomeWorkRelatPresenter homeWorkRelatPresenter;
    private HomeWorkPresenter homeWorkPresenter;
    public View mFooterView;
    //广告页面返回根本不需要在执行其他逻辑
    private boolean isResultRes = true;
    private Handler handler = new Handler() {
    };

    /**
     * 更新消息数值
     */
    @Override
    public boolean handleMessage(Message msg) {
        if (msg.what == NET_ERROR_TIP) {
            toastInCenter("网络不可用，请连接网络后重试");
        } else if (msg.what == DISMISS_NET_ERROR_TIP) {
            tv_net_tips.setVisibility(View.GONE);
        }
        return true;
    }

    @Override
    protected int setView() {
        return R.layout.activity_error_home_work;
    }

    @Override
    protected void findViews() {
        my_work_refresh_view = findViewById(R.id.my_work_refresh_view);
        expandableListView = findViewById(R.id.my_work_exlistv);
        mFooterView = getLayoutInflater().inflate(R.layout.work_footer, expandableListView, false);
        mFootViewParent = new LinearLayout(this);
        mFootViewParent.addView(mFooterView);
        ll_no_data = mFooterView.findViewById(R.id.ll_no_data);
        btn_join_class = mFooterView.findViewById(R.id.btn_join_class);
        mTvPlaceHold = mFooterView.findViewById(R.id.tv_place_hold);
        handle_go_to_bookdesk = mFooterView.findViewById(R.id.handle_go_to_bookdesk);
        handle_join_class = mFooterView.findViewById(R.id.handle_join_class);
        mTvNoDataTips = mFooterView.findViewById(R.id.tv_no_work_from_teacher_tip);
        mTvNoDataTips.setText(getResources().getString(R.string.error_work_book_compelted));
        tv_net_tips = findViewById(R.id.tv_net_tips);
    }

    @Override
    protected void initEvent() {
        btn_join_class.setOnClickListener(clickListener);
        expandableListView.setOnGroupClickListener(this);
        expandableListView.setOnChildClickListener(this);
        my_work_refresh_view.setOnHeaderRefreshListener(this);
        my_work_refresh_view.setOnFooterRefreshListener(this);

        setDownloadProgressOnDismissListener(new DownloadProgressBar.OnDownLoadDialogDismissListener() {
            @Override
            public void ondDismiss(DownloadProgressBar downloadProgressBar) {
                homeWorkPresenter.onDownloadProgressDismissListener(downloadProgressBar);

            }
        });
    }

    @Override
    protected void init() {
        setTitleText(R.string.error_work_book);
        application = (EApplication) getApplication();
        homeWorkRelatPresenter = new HomeWorkRelatPresenter(this, this, application);
        homeWorkPresenter = new HomeWorkPresenter(this, this);
        if (!EventBus.getDownLoadInstance().isRegistered(this)) {
            EventBus.getDownLoadInstance().register(this);
        }
        EventBus.getDefault().register(this);
        expandableListView.addFooterView(mFootViewParent);
        mHomeWorkAdapter = new HomeWorkAdapter(this, myWorks, 1, false);
        expandableListView.setAdapter(mHomeWorkAdapter);
    }

    @Override
    protected void loadData() {
        homeWorkPresenter.loadLocalData(SerializableManager.SerializeKey.SHARE_KEY_NOTIFICATION_ERROR_LIST);
        registerBoradcastReceiver();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!EventBus.getDownLoadInstance().isRegistered(this)) {
            EventBus.getDownLoadInstance().register(this);
        }
        if (isResultRes) {
            //获取本地未读消息
//            homeWorkRelatPresenter.getLocalMsgCount();
            refreshNoClassOrHomeworkHint();
        }
        //保证其他代码不变
        isResultRes = true;
        //签到
//        homeWorkRelatPresenter.signIn();
    }

    @Override
    public void onStop() {
        super.onStop();
        if (EventBus.getDownLoadInstance().isRegistered(this) && !isTopActivity()) {
            EventBus.getDownLoadInstance().unregister(this);
            hideDownloadProgress();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (EventBus.getDownLoadInstance().isRegistered(this)) {
            EventBus.getDownLoadInstance().unregister(this);
        }
        EventBus.getDefault().unregister(this);
        unregisterReceiver();
    }

    @Override
    public void setEnablePullLoadMoreDataStatus(boolean bool) {
        my_work_refresh_view.setEnablePullLoadMoreDataStatus(bool);
    }


    @Override
    public void loadLocalDataSucess(Object data) {
        isGetLocalSuccess = true;
        if (data != null) {
            List<MyWork> list = (List<MyWork>) data;
            myWorks.clear();
            myWorks.addAll(list);
            refreshUI();
        }
        hideCricleProgress();
        refreshNetData(true);
    }

    @Override
    public void getMyWorkListSucess(BasePaging<MyWork> workNotifyBasePaging, CopyOnWriteArrayList<MyWork> list) {
        try {
            isGetDataFromNet = true;
            hideCricleProgress();
            tv_net_tips.setVisibility(View.GONE);
            mPageCount = workNotifyBasePaging.getPageCount();
            if (list != null) {
                // 过滤掉未做过但已被撤销了的作业
                for (Iterator iterator = list.iterator(); iterator.hasNext(); ) {
                    MyWork myWork = (MyWork) iterator.next();

                    if (myWork.getIsDel() == 1) {// 已撤销 已删除
                        list.remove(myWork);
                    }
                }
                refreshListData(list);

                //如果只有一页，直接添加自主学习
                if (((list.size() == 0 || curPage > mPageCount) && !isRefresh) || mPageCount == 1 || mPageCount == 0) {
                    mFooterView.setVisibility(View.VISIBLE);
                    mTvPlaceHold.setVisibility(View.VISIBLE);
                    isTheLastPageShow = true;
                } else {
                    isTheLastPageShow = false;
                }
            }
            loadOver();
        } catch (Exception e) {
            e.getStackTrace();
        }
    }


    @Override
    public void getMyWorkListFail(Object data, String url) {
        isGetDataFromNet = true;
        hideCricleProgress();
        refreshNoClassOrHomeworkHint();
        if (data instanceof AuthFailureError) {
            EJumpManager.jumpToDialogActivity(this);
        } else if (EpagerErrcode.VOLLERY_AUTHENTICATION_I0EXCEPTION.equals(data.toString())) { //token 失效，volley 处理异常
            EJumpManager.jumpToDialogActivity(this);
        } else if (!NetworkUtils.isOnline()) {
            ToastUtil.INSTANCE.toastCenterNoNetError();
        } else {

        }
        FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_HOMEWORK_LIST, data == null ? "" : "失败信息：" + data.toString(), "获取未完成作业失败" + url, true);
        loadOver();
    }

    @Override
    public void _showDownloadProgress(String string) {
        showDownloadProgress(string);
    }

    @Override
    public void _hideDownloadProgress() {
        hideDownloadProgress();
    }

    @Override
    public void _showCricleProgress(String msg) {
        showCricleProgress(msg);
    }

    @Override
    public void _hideCricleProgress() {
        hideCricleProgress();
    }

    @Override
    public void _showCancelButtonOfDownloadProgress() {
        showCancelButtonOfDownloadProgress();
    }

    @Override
    public void _hideCancelButtonOfDownloadProgress() {
        hideCancelButtonOfDownloadProgress();
    }

    @Override
    public void _showToastError(int resId) {
        showToastError(resId);
    }

    @Override
    public void _showToastSuccess(int resId) {
        showToastSuccess(resId);
    }

    @Override
    public boolean _isProgressBarShowing() {
        return isDownloadProessBarShowing();
    }

    @Override
    public void _showWIFIDialog(DownLoadInfo downLoadInfo) {
        DialogUtil.showWIFIDialog(this, downLoadInfo);
    }

    @Override
    public boolean _isDownloadProgressBarShowing() {
        return isDownloadProessBarShowing();
    }

    @Override
    public void _updateDownloadProgress(int progress) {
        updateDownloadProgress(progress);
    }

    @Override
    public void _hideDownloadHorizontalProgressBar() {
        hideDownloadHorizontalProgressBar();
    }

    @Override
    public void onHeaderRefresh(PullToRefreshView view) {
        refreshNetData(true);
    }

    @Override
    public void onFooterRefresh(PullToRefreshView view) {
        refreshNetData(false);
    }

    @Override
    public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
        return true;
    }


    @Override
    public boolean onChildClick(ExpandableListView parent, View childView, int groupPosition, int childPosition, long id) {
        if (!DoubleClickCheckUtils.vertifyDuration()) {
            return false;
        }
        MyWork mCurrentMyWork = myWorks.get(groupPosition);
        WorkContents mCurrentWorkContents = mCurrentMyWork.getWorkContents().get(childPosition);
        if (!NetworkUtils.isOnline()) {
            ToastUtil.INSTANCE.toastCenterNoNetError();
            return false;
        }
        homeWorkPresenter.onChildClick(mCurrentMyWork, mCurrentWorkContents, groupPosition, childPosition, 1, false);
        return true;
//        return showGetSDcardPermissDialog(mCurrentMyWork, mCurrentWorkContents, groupPosition, childPosition);
    }

    private final int CODE_REQUEST_WRITESD_PERMISSION = 8800;
    private CWDialog getSDcardPermissDialog;

    /**
     * 获取SDcard权限提示框
     */
    private boolean showGetSDcardPermissDialog(final MyWork mCurrentMyWork, final WorkContents mCurrentWorkContents, final int groupPosition, final int childPosition) {
        boolean isHavePermiss = XXPermissionTool.isHasPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (isHavePermiss) {
            checkSDcardpermiss(mCurrentMyWork, mCurrentWorkContents, groupPosition, childPosition);
        } else {
            if (getSDcardPermissDialog == null) {
                getSDcardPermissDialog = new CWDialog(this);
                getSDcardPermissDialog.setTitle(R.string.get_permiss_title);
                getSDcardPermissDialog.setTitleTextColor(Color.BLACK);
                getSDcardPermissDialog.setMessage(getString(R.string.get_sdcard_permiss_content), 16, Color.BLACK, Gravity.LEFT);
                getSDcardPermissDialog.setPositiveButton(R.string.get_permiss_ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getSDcardPermissDialog.dismiss();
                        checkSDcardpermiss(mCurrentMyWork, mCurrentWorkContents, groupPosition, childPosition);
                    }
                });
                getSDcardPermissDialog.setNegativeButton(R.string.get_permiss_no, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getSDcardPermissDialog.dismiss();
                    }
                });
            }
            getSDcardPermissDialog.show();
        }
        return true;
    }

    /**
     * 使用sd卡，判断权限
     */
    private boolean checkSDcardpermiss(final MyWork mCurrentMyWork, final WorkContents mCurrentWorkContents, final int groupPosition, final int childPosition) {
        if (Build.VERSION.SDK_INT >= 23
                && getApplicationInfo().targetSdkVersion >= 23) {
            List<String> permissionList = new ArrayList<String>();
            Map<String, String> noteMap = new HashMap<>();
            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            noteMap.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, "读写本地存储权限");
            XXPermissionTool.checkPermissions(this, //
                    permissionList, //
                    noteMap, //
                    CODE_REQUEST_WRITESD_PERMISSION, //
                    new XXPermissionTool.OnCheckPermissionsFinishedListener() {
                        @Override
                        public void onCheckPermissionsFinished(int flag) {
                            if (0 == flag) {
                                homeWorkPresenter.onChildClick(mCurrentMyWork, mCurrentWorkContents, groupPosition, childPosition, 1, false);
                            } else {
//                                showConfirmCommitDialog(getActivity(), "未获取到读取相册权限，无法正常使用相册。");
                            }
                        }
                    });
        } else {
            homeWorkPresenter.onChildClick(mCurrentMyWork, mCurrentWorkContents, groupPosition, childPosition, 1, false);
        }
        return true;
    }

    public void onEventMainThread(EventBusFactory.DownloadEvent item) {
        homeWorkPresenter.onEventMainThread(item);
    }

    //隐藏加载框
    public void onEventMainThread(HideDownloadDialogBean hideDownloadDialogBean) {
        hideDownloadProgress();
    }

    private View.OnClickListener clickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!DoubleClickCheckUtils.vertify500Duration()) {
                return;
            }
            int i = v.getId();
            if (i == R.id.btn_join_class) {
                MeJumpManager.jumpToJoinClassActivity(R.string.go_back, ErrorWorkActivity.this, IntentValue.JumpToJoinClassType.TYPE_JOIN_CLASS, 0);
            }
        }
    };

    /**
     * 刷新网络数据(true为刷新，false为添加更多)
     *
     * @param boo
     */
    public void refreshNetData(boolean boo) {
        isRefresh = boo;
        if (isRefresh) {
            curPage = defult_page;
        }
        if (boo && myWorks.size() > 0 && NetworkUtils.isOnline()) {
            int footerViewsCount = expandableListView.getFooterViewsCount();
            if (footerViewsCount > 0) {
                mFooterView.setVisibility(View.GONE);
            }
        }
        homeWorkPresenter.getMyWorkList(0, curPage, LOAD_PAGE_SIZE, true, false);
    }

    @Override
    public void notifyDataSetChanged() {
        if (mHomeWorkAdapter != null)
            mHomeWorkAdapter.notifyDataSetChanged();
    }

    @Override
    public void getNetMsgCount() {
        homeWorkRelatPresenter.getNetMsgCount();
    }

    public void onEventMainThread(Answer answer) {
        try {
            MyWork tempMyWork = new MyWork();
            tempMyWork.setWorkId(answer.getWorkId());
            int index = myWorks.indexOf(tempMyWork);
            if (index != -1) {
                MyWork myWork = myWorks.get(index);
                List<WorkContents> workContentList = myWork.getWorkContents();
                WorkContents tempWorkContent = new WorkContents();
                tempWorkContent.setPackageId(answer.getPackageId());
                tempWorkContent.setcId(answer.getcId());
                tempWorkContent.setVersionId(answer.getVersionId());
                tempWorkContent.setParentVersionId(answer.getParentVersionId());
                int workIndex = workContentList.indexOf(tempWorkContent);
                if (workIndex != -1) {
                    float actualScore = answer.getActualScore();
                    float workcontentScore = 0;
                    WorkContents workContents = workContentList.get(workIndex);
                    boolean isRefresh = false;
                    if (answer.getSubmitStatus() == Answer.SubmitStatus.WORK_SUBMIT_SUCCUED) {
                        workContents.setSubmitCount(workContents.getSubmitCount() + 1);
                        workContents.setDoWorkPackageUrl(answer.getDoWorkPackageUrl());
                        isRefresh = true;
                    }
                    String showScore = workContents.getShowScore();
                    if (isScore(showScore)) {
                        workcontentScore = Float.valueOf(showScore);
                        if (actualScore > workcontentScore) {
                            workContents.setShowScore(actualScore + "");
                            isRefresh = true;
                        }
                    }

                    if (isRefresh) {
                        workContentList.set(workIndex, workContents);
                        myWork.setWorkContents(workContentList);
                        myWorks.set(index, myWork);
                        mHomeWorkAdapter.notifyDataSetChanged();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断字符串能否转为数字
     *
     * @param showScore
     * @return
     */
    public boolean isScore(String showScore) {
        try {
            //showScore.replace("-", "").matches("^[0-9]+$") 判断是否为整数
            //showScore.replace("-", "").matches("\\d+.\\d+") 判断是否为小数
            if (showScore.replace("-", "").matches("^[0-9]+$") || showScore.replace("-", "").matches("\\d+.\\d+")) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 刷新数据
     *
     * @param list 列表
     */
    private void refreshListData(List<MyWork> list) {
        if (isRefresh || curPage == defult_page) {
            myWorks.clear();
        }
        curPage++;// 请求下一页
        myWorks.addAll(list);
        refreshUI();
        if (isRefresh) {
            // 保存本地数据
            SerializableManager.getInstance().serialize(SerializableManager.SerializeKey.SHARE_KEY_NOTIFICATION_ERROR_LIST, (Serializable) myWorks);
        }
    }

    /**
     * 刷新UI
     */
    private void refreshUI() {
        mHomeWorkAdapter.notifyDataSetChanged();
        //        ll_no_data.setVisibility(View.GONE);
        my_work_refresh_view.setVisibility(View.VISIBLE);
        for (int i = 0; i < mHomeWorkAdapter.getGroupCount(); i++) {
            expandableListView.expandGroup(i);
        }
        refreshNoClassOrHomeworkHint();
        if (myWorks.isEmpty()) {
            //            my_work_refresh_view.setEnablePullLoadMoreDataStatus(false);
        } else {
            if (isRefresh) {
                my_work_refresh_view.setEnablePullLoadMoreDataStatus(true);// 设置启动加载更多
            }
        }
    }

    private void setTipsByRectentlyHomeWorkExecution(boolean hasWork, boolean hasOldWork) {
        if (hasWork) {
            mTvNoDataTips.setText(getResources().getString(R.string.homework_compelted));
        } else {
            mTvNoDataTips.setText(getResources().getString(R.string.no_assign_homework_yet));
        }
    }

    /**
     * 加载完成
     */
    private void loadOver() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (isRefresh) {
                    if (isTheLastPageShow) {
                        my_work_refresh_view.onHeaderRefreshComplete();
                        my_work_refresh_view.setFooterState(PullToRefreshView.PULL_TO_NO_MORE);
                    } else {
                        my_work_refresh_view.onHeaderRefreshComplete();
                    }

                } else {
                    if (isTheLastPageShow) {
                        my_work_refresh_view.onFooterRefreshComplete();
                        my_work_refresh_view.setFooterState(PullToRefreshView.PULL_TO_NO_MORE);
                    } else {
                        my_work_refresh_view.onFooterRefreshComplete();
                    }

                }
            }
        }, 500);

    }

    private void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(EpaperConstant.ACTION_PACKAGE_DELETE);
        myIntentFilter.addAction(EpaperConstant.BROADCAST_HOME_WORK_STATUS_CHANGE_MSG);
        myIntentFilter.addAction(EpaperConstant.INTENT_BOACK_REF_WORK);
        myIntentFilter.addAction(EpaperConstant.BROADCAST_HOME_WORK_STATUS_INTERACTIVE_TUTORIAL_FINASH);
        //注册广播
        registerReceiver(homeWorkPresenter.getBroadcastReceiver(), myIntentFilter);
    }

    private void unregisterReceiver() {
        if (homeWorkPresenter.getBroadcastReceiver() != null)
            unregisterReceiver(homeWorkPresenter.getBroadcastReceiver());
    }

    /**
     * 加入班级或者没作业提示
     * 有加班情况{1：有作业记录，没作业记录 }
     * 没加班情况{1：有作业记录，没作业记录 }
     */
    private void refreshNoClassOrHomeworkHint() {
        //加班成功后会回调
        Clazz clazz = application.getClazz();
        if (clazz == null && NetworkUtils.isOnline()) {//没加入班级情况下
            CWLog.e(TAG, "refreshNoClassOrHomeworkHint   checkClass(): 没加班");
            MeDao.getInstance().getClassList(EApplication.BRAND_ID, new BaseCallBack() {
                @Override
                public void success(Object data) {
                    final List<Clazz> clazzs = (List<Clazz>) data;
                    Clazz clazz = application.getClazz();
                    if (clazzs == null || clazzs.isEmpty()) {
                        clazz = null;
                    } else {
                        int indexOf = clazzs.indexOf(clazz);
                        if (indexOf < 0) {
                            indexOf = 0;
                        }
                        clazz = clazzs.get(indexOf);
                    }
                    SerializableManager.getInstance().serialize(SerializableManager.SerializeKey.SHARE_KEY_CLASS_DEFAULT, clazz);
                    SerializableManager.getInstance().serialize(SerializableManager.SerializeKey.SHARE_KEY_CLASS_LIST, (Serializable) clazzs);
                    application.setClazzs(clazzs);
                    application.setClazz(clazz);
                    checkClass();
                }

                @Override
                public void failed(int errorCode, Object data) {
                    CWLog.d(TAG, "拉取班级列表失败:" + errorCode);
                }

                @Override
                public void failed(Object data) {
                    CWLog.d(TAG, "拉取班级列表失败:" + data);
                }
            });
        } else {
            checkClass();
            CWLog.e(TAG, "refreshNoClassOrHomeworkHint   checkClass(): 加班了");
        }
    }

    private void checkClass() {
        Clazz clazz = application.getClazz();
        if (clazz == null && NetworkUtils.isOnline()) {//没加班情况下
            if (null != myWorks && myWorks.size() > 0) {
                //有作业记录,中间提示去掉，头部要有无加班提示
                setEmptyLayoutStatus2(STATUS_LAYOUT_HIDE_FOOTER);
                CWLog.e(TAG, "checkClass null:没有作业记录 hide");
            } else {
                //没有作业记录
                setEmptyLayoutStatus2(STATUS_LAYOUT_JOIN_CLASS);
            }
        } else {
            //有加班情况下包括加班成功后回调刷新UI
            if (null != myWorks && myWorks.size() > 0) {
                //有作业记录
                setEmptyLayoutStatus2(STATUS_LAYOUT_HIDE_FOOTER);
                CWLog.e(TAG, "checkClass not null:没有作业记录 hide");
            } else {
                //没有作业记录
                if (isGetDataFromNet || isGetLocalSuccess) {
                    setEmptyLayoutStatus2(STATUS_LAYOUT_HOMEWORK_COMPELETED);
                }
                CWLog.e(TAG, "checkClass not null:没有作业记录 ");
            }
        }
    }

    public static final int STATUS_LAYOUT_JOIN_CLASS = 1;
    public static final int STATUS_LAYOUT_HOMEWORK_COMPELETED = 2;
    public static final int STATUS_LAYOUT_HIDE_FOOTER = 3;

    private void setEmptyLayoutStatus2(int status) {
        if ((null != myWorks && myWorks.size() == 0) || (mPageCount > 0 && curPage > mPageCount)) {
            mFooterView.setVisibility(View.VISIBLE);
            //表示作业已经完成
            if (null != myWorks && myWorks.size() == 0) {
                if (status == STATUS_LAYOUT_JOIN_CLASS) {
                    handle_join_class.setVisibility(View.VISIBLE);
                    handle_go_to_bookdesk.setVisibility(View.GONE);
                } else if (status == STATUS_LAYOUT_HOMEWORK_COMPELETED) {
                    handle_join_class.setVisibility(View.GONE);
                    handle_go_to_bookdesk.setVisibility(View.VISIBLE);
                }
            } else {
                //从第二个条件进来的，仍然需要再判断一次
                handle_join_class.setVisibility(View.GONE);
                handle_go_to_bookdesk.setVisibility(View.GONE);
            }
        } else {
            if (null != myWorks && myWorks.size() > 0) {
                handle_join_class.setVisibility(View.GONE);
                handle_go_to_bookdesk.setVisibility(View.GONE);
            }
            if (mPageCount == 0 || curPage < mPageCount) {
                mTvPlaceHold.setVisibility(View.GONE);
            }

            if (handle_join_class.getVisibility() == View.GONE && handle_go_to_bookdesk.getVisibility() == View.GONE && mTvPlaceHold.getVisibility() == View.GONE) {
                mFooterView.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        hideCricleProgress();
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case RequestCode.HomeWorkFragmentResquestCode.REQ_ONLINE_ANSWER:
                    refreshNetData(true);
                    break;
                default:
                    break;
            }
        }
    }
}
